<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>系统界面</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!--    <link rel="stylesheet" href="../web/resource/css/allcss/allCss.css" type="text/css">-->
    <style>

    </style>
</head>
<body>
<div class="query-container">
    <div class="form-row">
        <!-- 部门名称 -->
        <div class="form-item">
            <label class="form-label">车架号：</label>
            <input type="text"
                   class="form-input"
                   placeholder="请输入车架号">
        </div>

<!--        &lt;!&ndash; 负责人 &ndash;&gt;-->
<!--        <div class="form-item">-->
<!--            <label class="form-label">负责人：</label>-->
<!--            <input type="text"-->
<!--                   class="form-input"-->
<!--                   placeholder="请输入负责人">-->
<!--        </div>-->

<!--        &lt;!&ndash; 状态选择 &ndash;&gt;-->
<!--        <div class="form-item">-->
<!--            <label class="form-label">状态：</label>-->
<!--            <select class="form-input form-select">-->
<!--                <option value="">全部</option>-->
<!--                <option value="1">启用</option>-->
<!--                <option value="0">停用</option>-->
<!--            </select>-->
<!--        </div>-->
    </div>
    <!-- 操作按钮 -->
    <div class="action-buttons">

        <button class="btn btn-reset">重置</button>
        <button class="btn btn-query">查询</button>
<!--        <button class="btn btn-add">新增</button>-->
    </div>
</div>
<div class="table-container">
    <table class="data-table">
        <thead class="data-table-thead">
        <tr>
            <!-- 固定列 -->
            <th>序号</th>
            <th>委托商</th>
            <th>批次号</th>
            <th>运单号</th>
            <th>车架号</th>
            <th>品牌</th>
            <th>型号</th>
            <th>运输方式</th>
            <th>起始地</th>
            <th>起始港</th>
            <th>目的港</th>
            <th>交车地</th>
            <th>计划时间</th>
            <th>当前位置</th>
            <th>状态</th>
            <!-- 动态运输段列 -->
            <template id="dynamic-columns">
                <th>供应商</th>
                <th>运输工具</th>
                <th>运输方式</th>
                <th>航次号</th>
                <th>装车地</th>
                <th>交车地</th>
                <th>装车时间</th>
                <th>交车时间</th>
            </template>
        </tr>
        </thead>
        <tbody>
        </tbody>
    </table>
    <!-- 分页 -->
</div>
<div class="pagination">
    <span>共0条</span>
    <select class="data-table-page" >
        <option class="" value="10" selected>10条/页</option>
        <option class="" value="20">20条/页</option>
        <option class="" value="50">50条/页</option>
    </select>
    <div class="page-num">
        <button class="pre-button">＜</button>
        <span>1</span>
        <button class="next-button">＞</button>
    </div>
</div>
<script>
    const nextButton = document.querySelector('.next-button')
    const preButton = document.querySelector('.pre-button')
    //渲染
    function renderTable(data) {
        document.querySelector('.pagination span:first-child')
            .textContent = `共${data.data.total}条`;
        const tbody = document.querySelector('.data-table tbody');

        // 更新页码显示
        document.querySelector('.page-num span').textContent = data.data.current;

        if (data.data.current >= data.data.pages){
            nextButton.disabled = true;
            nextButton.style.opacity = "0.5";
        }else {
            nextButton.disabled = false;
            nextButton.style.opacity = "1";
        }

        if (data.data.current <= 1){
            preButton.disabled = true;
            preButton.style.opacity = "0.5";
        }else {
            preButton.disabled = false;
            preButton.style.opacity = "1";
        }
        renderDynamicHeaders(data);

        tbody.innerHTML = ''; // 清空旧数据
        data.data.records.
        slice( // 根据分页参数切割数据
            (data.data.current - 1)
            * data.data.size,
            data.data.current * data.data.size
        ).forEach((item, index) => {
            const tr = document.createElement('tr');

            // 生成表格内容
            tr.innerHTML = `
                <td>${(data.data.current - 1) * data.data.size + index + 1}</td>
                 <td>${item.consignorName || ''}</td>
                <td>${item.batchNumber || ''}</td>
                <td>${item.waybillNo || ''}</td>
                <td>${item.frameNumber || ''}</td>
                <td>${item.brandName || ''}</td>
                <td>${item.modelName || ''}</td>
                <td>${getTransportMode(item.transportMode)}</td>
                <td>${item.departurePlace || ''}</td>
                <td>${item.departurePort || ''}</td>
                <td>${item.arrivePort || ''}</td>
                <td>${item.collectCar || ''}</td>
                <td>${formatDateTime(item.planDate)}</td>
                <td>${item.actualPositionName || ''}</td>
                <td>${getStatusText(item.state)}</td>

    `;
            // 动态运输段数据
            if (item.objectDate && item.objectDate.length > 0) {
                item.objectDate.forEach(transport => {
                    tr.innerHTML += `
                    <td>${transport.supplierName || ''}</td>
                    <td>${transport.transport || ''}</td>
                    <td>${transport.transportType || ''}</td>
                    <td>${transport.voyageNumber || ''}</td>
                    <td>${transport.loadingPlace || ''}</td>
                    <td>${transport.deliveryPlace || ''}</td>
                    <td>${formatDateTime(transport.loadingDate)}</td>
                    <td>${formatDateTime(transport.deliveryDate)}</td>
                `;
                });
            }
            tbody.appendChild(tr);
        });
    }
    document.querySelector('.btn-query').addEventListener('click',function (){
        fetchData('query');
    })
    document.querySelector('.pre-button').addEventListener('click',function (){
        fetchData('pre');
    })
    document.querySelector('.next-button').addEventListener('click',function (){
        fetchData('next');
    })
    // 统一请求方法
    async function fetchData(type) {

        let { page, pageSize } = getPaginationParams();
        if (type === 'pre') {
            page = Math.max(1, page - 1)  // 确保页码不小于1
            document.querySelector('.page-num span').textContent = page  // 同步更新页码显示
        }else if (type === 'next'){
            page = Math.max(1, page + 1)  // 确保页码不小于1
            document.querySelector('.page-num span').textContent = page  // 同步更新页码显示
        }
        const queryParams = {
            frameNumber: document.querySelector('input[placeholder="请输入车架号"]').value,
            // leader: document.querySelector('input[placeholder="请输入负责人"]').value,
            // status: document.querySelector('.form-select').value,
            page: page,
            rows: pageSize
        };

        // try {
            const response = await fetch('http://localhost:8080/transportChild/deployPageList', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(queryParams)
            });

            const data = await response.json();
            if (data.status === 0) {
                renderTable(data);
            }else  if (data.status === -1) {
                console.error('请求失败:', error);
            }
        // } catch (error) {
        //     console.error('请求失败:', error);
        //     renderTable({ data: { records: [], total: 0, current: 1, pages: 0 } });
        // }
    }
    //重置按钮
    document.querySelector('.btn-reset').addEventListener('click',()=>{
        document.querySelectorAll('.form-input').forEach(input => {
            if (input.type === 'text') input.value = '' // 清空文本输入
            if (input.tagName === 'SELECT') input.value = '' // 重置选择框
        });

    })

    // 关闭弹窗
    document.querySelectorAll('.modal-close-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            this.closest('.modal-mask').style.display = 'none';
        });
    });

    document.querySelectorAll('.btn-close').forEach(btn => {
        btn.addEventListener('click', function() {
            this.closest('.modal-mask').style.display = 'none';
        });
    });

    // 辅助函数
    function getTransportMode(mode) {
        const modes = {1: '公路', 2: '水路', 3: '水陆联运'};
        return modes[mode] || '未知';
    }

    function getStatusText(state) {
        const statusMap = {0: '待分配', 1: '已分配', 2: '运输中', 3: '已交车'};
        return statusMap[state] || '未知状态';
    }
    function formatDateTime(dateStr) {
        if (!dateStr) return '';
        const date = new Date(dateStr);
        return date.toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit'
        });
    }

    // 动态生成表头
    function renderDynamicHeaders(data) {
        const thead = document.querySelector('.data-table-thead tr');
        // 清空之前的动态列
        const existingHeaders = thead.querySelectorAll('.dynamic-header');
        existingHeaders.forEach(header => header.remove());

        // 获取第一个记录的运输段数量（假设所有记录结构相同）
        const sampleItem = data.data.records[0];
        if (sampleItem && sampleItem.objectDate) {
            sampleItem.objectDate.forEach((_, index) => {
                const headers = [
                    '供应商', '运输工具', '运输方式', '航次号',
                    '装车地', '交车地', '装车时间', '交车时间'
                ];
                headers.forEach(headerText => {
                    const th = document.createElement('th');
                    th.className = 'dynamic-header';
                    th.textContent = `${headerText}（段${index + 1}）`; // 添加段序号
                    thead.appendChild(th);
                });
            });
        }
    }
</script>
</body>
